﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Telerik.WebControls;
using System.Text;

namespace Runda.CMS.Portal.SalesManage
{
    public partial class QueryBillsEx : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", ""));
                //ddlCompany.SelectedValue = "";

                if (ddlCompany.SelectedValue != null && ddlCompany.SelectedValue != "")
                {
                    BudgetBll bll = new BudgetBll();
                    string UnlockYearmonth = bll.GetunLockMonth(ddlCompany.SelectedValue);
                    ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                    ddlBudgetMonth1.SelectedValue = UnlockYearmonth.Substring(5, 2);
                }

                BindGrid(1);
                Calculate();

               }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid(1);
            Calculate();
        }

        private void SalesbillImportstatus(string company, string sYear, string sMonth)
        { 
            BudgetBll bll = new BudgetBll();
            if (bll.BillDataStatus(sYear, sMonth, company) == 1)
            { 
                msg.Text = "已关账！";
                hidMsg.Value = "1";
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
            }
            else
            { 
                msg.Text = "";
                hidMsg.Value = "0";
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
            }
        }
        protected void btnRefershBillInfo_Click(object sender, EventArgs e)
        {
            
        }

        protected void btnSaveSubItems_Click(object sender, EventArgs e)
        {
           
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        } 

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().GetSalesBills(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);

            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        private void Calculate()
        {
            string sb = getWhereClause();

            BudgetBll bll = new BudgetBll();
            DataTable dt = bll.CalcbillAmount(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                lblTotal.Text = "合计：   金额："+string.Format("{0:N}", dt.Rows[0]["iNatMoney"])+"；价税合计："+string.Format("{0:N}", dt.Rows[0]["iNatSum"]);
 

            }
            else
            {

                lblTotal.Text = "";
            }
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }

        private string getWhereClause()
        { 
            StringBuilder sb = new StringBuilder();
            string beginDT, endDT;
            
            beginDT = ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth.SelectedValue + "-01";
            endDT = DataValid.Monthlastday(ddlBudgetYear.SelectedValue + "-" + ddlBudgetMonth.SelectedValue + "-01");
            
            sb.Append(" and a.[dDate]  between '").Append(beginDT+"' and '").Append(endDT+"'");

            if (this.txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and c.[CustomerName]  like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }
            if (ddlStatType.SelectedValue=="1")
            { sb.Append(" and a.cCusCode in(select customerCode from cms_Bg_InnerCustomer)"); }
            else if (ddlStatType.SelectedValue == "2")
            { sb.Append(" and a.cCusCode not in(select customerCode from cms_Bg_InnerCustomer)"); }

            if (ddlSourceType.SelectedValue == "1")
            { sb.Append(" and a.Sourcetype in(1,2)"); }
            else if (ddlSourceType.SelectedValue == "2")
            { sb.Append(" and a.Sourcetype =3"); }

            sb.Append(" and billUnit in (select d.DepartmentName from Cms_Sys_UserDepartment_DataRight a inner join Cms_Sys_Department d on d.DepartmentID = a.DepartmentID where d.isCompany = 1 and a.UserID = '" + base.CurrentUserID.ToString() + "')");

            //int RecordCount = 0;
            //RecordCount = new BudgetBll().getDataright(base.CurrentUserID.ToString());

            //if (RecordCount == 0)
            //{ sb.Append(" and ([productmanager] ='").Append(base.CurrentUserEntity.UserName).Append("'").Append(" or [biller] ='").Append(base.CurrentUserID.ToString()).Append("')"); }
            //else
            //{ sb.Append(" and [productmanager] in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))"); }

            if (ddlCompany.SelectedValue != "")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }
            
            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and a.cCusCode in(").Append("select CustomerCode from cms_ctrt_customer where customername like '%").Append(txtCustomerName.Text.Trim()).Append("%')");
            }

            sb.Append(" and BillUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
            
            
            
            return sb.ToString();
        }

        protected void gridContractItems_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                if (dv != null)
                {
                    RadNumericTextBox txtiNatSum_adjust = e.Item.FindControl("txtiNatSum_adjust") as RadNumericTextBox;
                    txtiNatSum_adjust.Value = Convert.ToDouble(dv["iNatSum_adjust"].ToString());
                }
            }
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string Whereclause = getWhereClause();

            BillBll bll = new BillBll();

            DataTable dt = bll.GetSalesBills_export(Whereclause);

            Export.Export2Excel(dt, "账套数据一览表", Page.Response);

        }

        protected void lnkbtnSubmit_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            bll.SubmmitBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
            

        }

        protected void lnkbtnCheck_Click(object sender, EventArgs e)
        {

            BudgetBll bll = new BudgetBll();
            //bll.CheckBudget(ddlBudgetYear.SelectedValue.ToString(), base.CurrentUserEntity.UserName);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            //ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "showprocessbar();", true);
            BudgetBll bll = new BudgetBll();
            string company,sYear,sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company=="") {
                msg.Text = "请选择开票公司。";
                return;}
            if (bll.BillDataStatus(sYear,sMonth,company)==1)
            {
                msg.Text = "选择月份的销售数据（导入）已关账";
                return;
            }
            if (bll.AccountCloseStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "选择月份的销售数据已关账";
                return;
            }
            if (bll.PreBillDataStatus(sYear, sMonth, company) > 0)
            {
                msg.Text = "当前月份之前的销售数据导入未完成，无法导入当前月份数据";
                return;
            }
            
            msg.Text = "数据导入中，请等待!";
            
            string budgetYearmonth="";

            budgetYearmonth = ddlBudgetYear.SelectedValue.ToString() + "-" + ddlBudgetMonth.SelectedValue.ToString() + "-01";
            bll.syncUFBills(budgetYearmonth, ddlCompany.SelectedValue);
            
            //ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "unshowprocessbar();", true);
            msg.Text = "数据导入已完成。";
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
           
            BudgetBll bll = new BudgetBll();
            string company, sYear, sMonth;
            company = ddlCompany.SelectedValue.ToString();
            sYear = ddlBudgetYear.SelectedValue.ToString();
            sMonth = ddlBudgetMonth.SelectedValue.ToString();

            if (company == "")
            {
                msg.Text = "请选择开票公司。";
                return;
            }

            if (bll.BillDataStatus(sYear, sMonth, company) == 1)
            {
                msg.Text = "选择月份的销售数据（导入）已关账";
                return;
            }

            bll.setDataStatus(sYear, sMonth, company, "1", base.CurrentUserEntity.UserName, DateTime.Now);
            msg.Text = "成功关闭销售数据导入。";
        }

        protected void ddlBudgetMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            initOpeate();
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCompany.SelectedValue != "")
            {
                BudgetBll bll = new BudgetBll();
                string UnlockYearmonth = bll.GetunLockMonth(ddlCompany.SelectedValue);
                ddlBudgetMonth.SelectedValue = UnlockYearmonth.Substring(5, 2);
                ddlBudgetMonth1.SelectedValue = UnlockYearmonth.Substring(5, 2);

                SalesbillImportstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);
            }
            initOpeate();

        }

        protected void ddlBudgetMonth1_SelectedIndexChanged(object sender, EventArgs e)
        {
            initOpeate();
        }

        private void initOpeate()
        {
            if (ddlBudgetMonth.SelectedValue == ddlBudgetMonth1.SelectedValue && ddlCompany.SelectedValue!="")
            {
                Button1.Enabled = true;
                Button3.Enabled = true;
                Button4.Enabled = true;
                SalesbillImportstatus(ddlCompany.SelectedValue, ddlBudgetYear.SelectedValue, ddlBudgetMonth.SelectedValue);

            }
            else
            {
                Button1.Enabled = false;
                Button3.Enabled = false;
                Button4.Enabled = false;
            }
        }
    }
}
